/**
 * 
 */
package org.tuestudent.grouppa;

import org.tuestudent.grouppa.AppContext.ActiveScreens;

/**
 * @author s121170 A class that periodically sends requests to the server to
 *         provide relevant updates and notifications
 */
public class PeriodicUpdater implements Runnable {

    private final int interval;
    private volatile boolean cancel = false;
    public volatile boolean pause = false;
    public void stop()
    {
        cancel = true;
    }

    /**
     * runs periodic updater until it will be stopped
     * periodic updater will periodically send requests for new chat messages
     * @param interval interval in milliseconds
     */
    public PeriodicUpdater(int interval) {
        this.interval = interval;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        //CHECK: automatically send every interval milliseconds
        // request for new chat messages
        AppContext ctx = Main.getContext();
        ChatViewController CVC = ChatViewController.getInstance();
        WallViewController WVC = WallViewController.getInstance();
        while(!cancel)
        {
            if(!pause && ctx.activeScreen == ActiveScreens.grouppaScreen && ctx.currentUserName != null && ctx.getCurrentGroup() != null)
            {
                CVC.getNewMessages();
                
                if(ctx.currentGrouppaFragment instanceof ViewTopic)
                {
                    WVC.getNewComments(((ViewTopic)ctx.currentGrouppaFragment).topicId);
                }
                else
                {
                    WVC.getChangedTopics();
                }
            }
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                break;
            }
        }
    }


}
